import { reqGetAllUser } from "@/api/reqUser";
import type { USER } from "@/types/user";
import { defineStore, storeToRefs } from "pinia";
import { ref, computed, onMounted } from "vue";
import { useRoleStore } from "./useRoleStore";

export const useUsersStore = defineStore("users", function () {
  // 拿到所有角色
  const roleStore = useRoleStore();
  const { roleList } = storeToRefs(roleStore);
  const userList = ref<USER[]>([]);
  const getAllUser = async () => {
    const { data } = await reqGetAllUser();
    userList.value = data;
  };

  const tearchList = computed(() => {
    // 1. 角色为老师的角色ID
    const id = roleList.value.find((role) => role.name == "老师")?._id;
    // 2. 根据角色ID筛选用户
    return userList.value.filter((user) => user.role_id === id);
  });
  const manageList = computed(() => {
    // 1. 角色为老师的角色ID
    const id = roleList.value.find((role) => role.name == "学管")?._id;
    // 2. 根据角色ID筛选用户
    return userList.value.filter((user) => user.role_id === id);
  });

  onMounted(() => {
    getAllUser();
  });

  return {
    getAllUser,
    tearchList,
    manageList,
  };
});
